package com.tamtamy.jtta.data.xml;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.tamtamy.jtta.data.ContentList;
import com.tamtamy.jtta.exception.NoResultException;
import com.tamtamy.jtta.exception.ParsingException;

public class XMLContentList extends ContentList {

	private static final long serialVersionUID = -6457987963376056823L;

	private static final String KCLCONTENT = "it.reply.tt.rest.entity.KcLContent";
	
	public XMLContentList(Document xmlDocument) throws NoResultException, ParsingException {
		super();
		NodeList contentNodeList = xmlDocument.getElementsByTagName(KCLCONTENT);
		if (contentNodeList == null || contentNodeList.getLength()==0){
			throw new NoResultException("No " + KCLCONTENT + " element found");
		}
		for (int i = 0; i < contentNodeList.getLength(); i++) {
			Node contentNode = contentNodeList.item(i);
			try {
				Document contentDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
				contentDocument.appendChild(contentDocument.importNode(contentNode, true));
				this.add(new XMLContent(contentDocument)); 
			} catch (ParserConfigurationException parserConfigurationException) {
				throw new ParsingException("Error parsing " + KCLCONTENT + " element : " + parserConfigurationException.getMessage());
			}  
		}
	}
}
